package org.hongzhisoft.dis.dao;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.hongzhisoft.dis.bean.Role;
import org.hongzhisoft.dis.util.DataSourceTools;

/**
 * 角色数据持久处理类
 * 
 * @author HongChengzhi
 *
 */
public class RoleDao {

    private DataSource dataSource = DataSourceTools.getDataSource();

    private final static String SELECT_ALL =
            "select role_id, role_name, role_key, status, remark, is_delete as 'isDelete' from t_role where is_delete=0";
    private final static String SELECT_BY_ID =
            "select role_id, role_name, role_key, remark, is_delete as 'isDelete' from t_role where role_id = ?";
    private final static String INSERT_SQL =
            "insert into t_role(role_name,role_key,remark) value(?,?,?)";
    private final static String UPDATE_SQL =
            "update t_role set role_key = ?,remark = ? where role_id = ?";
    private final static String DELETE_SQL =
            "update t_role set is_delete=1 where role_id = ?";
    private final static String STATUS_CHANGE_SQL=
            "update t_role set status=? where role_id = ?";


    public List<Role> selectAll() throws SQLException {

        QueryRunner queryRunner = new QueryRunner(dataSource);

        List<Role> roles = queryRunner.query(SELECT_ALL,
                new BeanListHandler<Role>(Role.class));

        return roles;
    }

    public Role selectById(int id) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(dataSource);

        Role role = queryRunner.query(SELECT_BY_ID,
                new BeanHandler<Role>(Role.class), id);

        return role;

    }

    public int insertRole(Role role) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(dataSource);
        return queryRunner.update(INSERT_SQL, role.getRole_name(),
                role.getRole_key(), role.getRemark());
    }

    public int updateRole(Role role) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(dataSource);
        int result = queryRunner.update(UPDATE_SQL, role.getRole_key(),
                role.getRemark(), role.getRole_id());
        return result;
    }

    public int deleteRole(int id) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(dataSource);
        int result = queryRunner.update(DELETE_SQL, id);

        return result;
    }
    
    public int statusChangeRole(int status, int id) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(dataSource);
        int result = queryRunner.update(STATUS_CHANGE_SQL, status,id);

        return result;
    }
    
}
